package ynu;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.UUID;

public class Reception extends User {
    private String username;
    public Reception(String username) {
        this.username = username;
    }
    // 日期格式化器
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    // 数据文件路径
    private final String MOVIE_FILE = "D:\\java实训大作业\\影片信息.txt";
    private final String SALE_FILE = "D:\\java实训大作业\\销售数据.txt";
    private final String THEATER_FILE = "D:\\java实训大作业\\放映厅信息.txt";
    private final String SHOW_FILE = "D:\\java实训大作业\\场次信息.txt";
    private final String LOG_FILE = "D:\\java实训大作业\\日志文件.txt";

    // 列出所有正在上映的影片
    public void listAllMovies() {
        System.out.println("\n===== 正在上映影片 =====");
        try {
            File file = new File(MOVIE_FILE);
            if (!file.exists()) {
                System.out.println("暂无影片信息！");
                return;
            }

            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    String[] parts = line.split("\\|");
                    // 影片信息格式：片名|导演|主演|剧情简介|时长|评分|上映状态
                    System.out.println("片名: " + parts[0]);
                    System.out.println("导演: " + parts[1]);
                    System.out.println("主演: " + parts[2]);
                    System.out.println("剧情简介: " + parts[3]);
                    System.out.println("时长: " + parts[4] + "分钟");
                    System.out.println("评分: " + parts[5]);
                    System.out.println("---------------------");
                }
            }
            br.close();
        } catch (IOException e) {
            System.out.println("读取影片信息失败：" + e.getMessage());
            log("读取影片信息失败：" + e.getMessage());
        }
    }

    //列出所有场次信息
    public void listAllShows() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n===== 场次查询 =====");
        System.out.println("1. 最近一周");
        System.out.println("2. 当日场次");
        System.out.println("3. 近三天");
        System.out.print("请选择查询范围: ");

        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine());
            List<Show> allShows = Show.readShows();
            List<Show> filteredShows = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date now = new Date();

            switch (choice) {
                case 1: // 未来一周
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.DAY_OF_YEAR, 7);
                    Date oneWeekLater = cal.getTime();

                    for (Show s : allShows) {
                        if (s.getShowTime().after(now) && s.getShowTime().before(oneWeekLater)) {
                            filteredShows.add(s);
                        }
                    }
                    break;

                case 2: // 当日
                    cal = Calendar.getInstance();
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    Date todayStart = cal.getTime();

                    cal.add(Calendar.DAY_OF_YEAR, 1);
                    Date tomorrowStart = cal.getTime();

                    for (Show s : allShows) {
                        if (s.getShowTime().after(todayStart) && s.getShowTime().before(tomorrowStart)) {
                            filteredShows.add(s);
                        }
                    }
                    break;

                case 3: // 未来三天
                    cal = Calendar.getInstance();
                    cal.add(Calendar.DAY_OF_YEAR, 3);
                    Date threeDaysLater = cal.getTime();

                    for (Show s : allShows) {
                        if (s.getShowTime().after(now) && s.getShowTime().before(threeDaysLater)) {
                            filteredShows.add(s);
                        }
                    }
                    break;

                default:
                    System.out.println("无效的选择！");
                    return;
            }

            // 按时间排序
            filteredShows.sort(Comparator.comparing(Show::getShowTime));

            // 显示结果
            if (filteredShows.isEmpty()) {
                System.out.println("该范围内没有场次！");
            } else {
                System.out.println("\n===== 场次信息 =====");
                for (Show s : filteredShows) {
                    System.out.println("场次ID: " + s.getId());
                    System.out.println("影片名: " + s.getMovieName());
                    System.out.println("放映厅: " + s.getTheaterName());
                    System.out.println("放映时间: " + sdf.format(s.getShowTime()));
                    System.out.println("票价: " + s.getPrice() + "元");
                    System.out.println("---------------------");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        }
    }

    // 列出指定电影和场次的信息
    public void listSpecificShowInfo() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入影片名: ");
        String movieName = scanner.nextLine();
        System.out.print("请输入场次ID: ");
        String showId = scanner.nextLine();

        try {
            List<Show> shows = Show.readShows();
            Show targetShow = shows.stream()
                    .filter(s -> s.getId().equals(showId) && s.getMovieName().equals(movieName))
                    .findFirst()
                    .orElse(null);

            if (targetShow == null) {
                System.out.println("未找到指定的电影场次信息！");
                return;
            }

            System.out.println("\n===== 场次详情 =====");
            System.out.println("场次ID: " + targetShow.getId());
            System.out.println("影片名: " + targetShow.getMovieName());
            System.out.println("放映厅: " + targetShow.getTheaterName());
            System.out.println("放映时间: " + sdf.format(targetShow.getShowTime()));
            System.out.println("票价: " + targetShow.getPrice() + "元");

            // 获取座位信息
            char[][] seatMap = targetShow.getSeatMap();
            int rows = targetShow.getRows();
            int cols = targetShow.getCols();

            System.out.println("\n===== 座位信息 =====");
            // 打印列号
            System.out.print("  ");
            for (int j = 0; j < cols; j++) {
                System.out.printf("%2d", j + 1);
            }
            System.out.println();

            // 打印行和座位状态
            int availableSeats = 0;
            for (int i = 0; i < rows; i++) {
                System.out.print((i + 1) + " ");
                for (int j = 0; j < cols; j++) {
                    System.out.printf("%2c", seatMap[i][j]);
                    if (seatMap[i][j] == 'O') availableSeats++;
                }
                System.out.println();
            }

            System.out.println("\n总座位数: " + (rows * cols));
            System.out.println("空闲座位数: " + availableSeats);
            System.out.println("O: 空闲座位  X: 已售座位");

        } catch (Exception e) {
            System.out.println("读取场次信息失败：" + e.getMessage());
            log("读取场次信息失败：" + e.getMessage());
        }
    }

    // 售票功能
    public void sellTickets() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入影片名: ");
        String movieName = scanner.nextLine();
        System.out.print("请输入场次ID: ");
        String showId = scanner.nextLine();

        try {
            // 读取所有场次信息
            List<Show> shows = Show.readShows();
            Show targetShow = null;
            int showIndex = -1;

            // 查找目标场次
            for (int i = 0; i < shows.size(); i++) {
                Show s = shows.get(i);
                if (s.getId().equals(showId) && s.getMovieName().equals(movieName)) {
                    targetShow = s;
                    showIndex = i;
                    break;
                }
            }

            if (targetShow == null) {
                System.out.println("未找到指定的电影场次信息！");
                return;
            }

            System.out.println("找到场次信息：");
            System.out.println("影片名: " + targetShow.getMovieName() +
                    " 放映厅: " + targetShow.getTheaterName() +
                    " 放映时间: " + sdf.format(targetShow.getShowTime()) +
                    " 票价: " + targetShow.getPrice() + "元");

            // 获取座位图
            char[][] seatMap = targetShow.getSeatMap();
            int rows = targetShow.getRows();
            int cols = targetShow.getCols();

            // 显示当前座位状态
            System.out.println("\n当前座位状态：");
            // 打印列号
            System.out.print("  ");
            for (int j = 0; j < cols; j++) {
                System.out.printf("%2d", j + 1);
            }
            System.out.println();

            // 打印行和座位状态
            for (int i = 0; i < rows; i++) {
                System.out.print((i + 1) + " ");
                for (int j = 0; j < cols; j++) {
                    System.out.printf("%2c", seatMap[i][j]);
                }
                System.out.println();
            }

            // 选择座位
            System.out.print("\n请输入要购买的座位数: ");
            int ticketCount = Integer.parseInt(scanner.nextLine());

            List<String> seats = new ArrayList<>();
            for (int i = 0; i < ticketCount; i++) {
                System.out.print("请输入第" + (i + 1) + "个座位(格式: 行号,列号): ");
                String seat = scanner.nextLine();
                seats.add(seat);
            }

            // 检查座位是否可用
            boolean allAvailable = true;
            for (String seat : seats) {
                String[] coords = seat.split(",");
                int row = Integer.parseInt(coords[0]) - 1;
                int col = Integer.parseInt(coords[1]) - 1;

                if (row < 0 || row >= rows || col < 0 || col >= cols) {
                    System.out.println("座位 " + seat + " 不存在！");
                    allAvailable = false;
                    break;
                }

                if (seatMap[row][col] == 'X') {
                    System.out.println("座位 " + seat + " 已售出！");
                    allAvailable = false;
                    break;
                }
            }

            if (!allAvailable) {
                System.out.println("售票失败，请重新选择座位！");
                return;
            }

            // 检查是否有儿童票
            System.out.print("是否有儿童票？(1-是, 0-否): ");
            int hasChild = Integer.parseInt(scanner.nextLine());
            int childCount = 0;
            if (hasChild == 1) {
                System.out.print("请输入儿童票数量: ");
                childCount = Integer.parseInt(scanner.nextLine());
                if (childCount > ticketCount) {
                    System.out.println("儿童票数量不能超过总票数！");
                    return;
                }
            }

            // 计算票价（儿童票半价）
            double price = targetShow.getPrice();
            double totalPrice = (ticketCount - childCount) * price + childCount * price * 0.5;

            // 检查是否有早场折扣（早上10点前）
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(targetShow.getShowTime());
            int hour = calendar.get(Calendar.HOUR_OF_DAY);

            if (hour < 10) {
                totalPrice *= 0.9;
                System.out.println("早场优惠：9折！");
            }

            System.out.println("总票价: " + String.format("%.2f", totalPrice) + "元");
            System.out.print("请输入支付金额: ");
            double payment = Double.parseDouble(scanner.nextLine());

            if (payment < totalPrice) {
                System.out.println("支付金额不足，售票失败！");
                return;
            }

            // 更新座位状态
            for (String seat : seats) {
                String[] coords = seat.split(",");
                int row = Integer.parseInt(coords[0]) - 1;
                int col = Integer.parseInt(coords[1]) - 1;
                seatMap[row][col] = 'X';
            }

            // 保存更新后的场次信息
            Show.saveShows(shows);

            // 生成电子票号
            String ticketId = UUID.randomUUID().toString();

            // 记录销售数据
            String saleRecord = targetShow.getMovieName() + "|" +
                    targetShow.getTheaterName() + "|" +
                    sdf.format(targetShow.getShowTime()) + "|" +
                    String.join(";", seats) + "|" +
                    ticketId + "|" +
                    String.format("%.2f", totalPrice) + "|" +
                    sdf.format(new Date()) + "|" +
                    "false";

            // 保存销售记录
            saveSaleRecord(saleRecord);

            // 打印电影票信息
            System.out.println("\n===== 电影票信息 =====");
            System.out.println("电子票号: " + ticketId);
            System.out.println("影片名: " + targetShow.getMovieName());
            System.out.println("放映厅: " + targetShow.getTheaterName());
            System.out.println("放映时间: " + sdf.format(targetShow.getShowTime()));
            System.out.println("座位: " + String.join(", ", seats));
            System.out.println("总金额: " + String.format("%.2f", totalPrice) + "元");
            System.out.println("找零: " + String.format("%.2f", payment - totalPrice) + "元");
            System.out.println("======================");

            log("用户 " + username + " 售出电影票，票号: " + ticketId + "，影片: " + targetShow.getMovieName());
            System.out.println("售票成功！");

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        } catch (Exception e) {
            System.out.println("售票失败：" + e.getMessage());
            log("售票失败：" + e.getMessage());
        }
    }

    // 保存销售记录
    private void saveSaleRecord(String record) throws IOException {
        File file = new File(SALE_FILE);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
        bw.write(record);
        bw.newLine();
        bw.close();
    }

    //退票功能
    public void refundTicket() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入电子票号: ");
        String ticketId = scanner.nextLine();

        try {
            // 1. 查找销售记录
            List<String> sales = new ArrayList<>();
            String targetSale = null;
            int targetIndex = -1;

            File saleFile = new File(SALE_FILE);
            if (!saleFile.exists()) {
                System.out.println("暂无销售记录！");
                return;
            }

            BufferedReader saleBr = new BufferedReader(new FileReader(saleFile));
            String line;
            while ((line = saleBr.readLine()) != null) {
                sales.add(line);
                if (!line.trim().isEmpty()) {
                    String[] parts = line.split("\\|");
                    // 格式: 影片名|放映厅|放映时间|座位|电子票号|价格|购买时间|是否退票
                    if (parts.length >= 8 && parts[4].equals(ticketId)) {
                        targetSale = line;
                        targetIndex = sales.size() - 1;
                    }
                }
            }
            saleBr.close();

            if (targetSale == null) {
                System.out.println("未找到指定的电子票信息！");
                return;
            }

            String[] saleParts = targetSale.split("\\|");
            String movieName = saleParts[0];
            String theaterName = saleParts[1];
            String showTimeStr = saleParts[2];

            // 2. 解析放映时间
            Date showTime = sdf.parse(showTimeStr);

            // 3. 检查退票时间限制
            Date now = new Date();
            long diff = showTime.getTime() - now.getTime();
            long hours = diff / (60 * 60 * 1000);

            if (hours < 1) {
                System.out.println("距离电影上映不足1小时，无法退票！");
                return;
            }

            // 4. 检查是否已退票
            if (saleParts.length > 7 && "true".equals(saleParts[7])) {
                System.out.println("该票已退，无法重复退票！");
                return;
            }

            // 5. 查找匹配的场次
            List<Show> shows = Show.readShows();
            Show targetShow = null;
            SimpleDateFormat matchSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (Show show : shows) {
                // 使用影片名、放映厅和时间进行匹配
                if (show.getMovieName().equals(movieName) &&
                        show.getTheaterName().equals(theaterName) &&
                        matchSdf.format(show.getShowTime()).equals(showTimeStr)) {

                    targetShow = show;
                    break;
                }
            }

            if (targetShow == null) {
                System.out.println("未找到对应的场次信息，退票失败！");
                return;
            }

            // 6. 计算退款金额
            double price = Double.parseDouble(saleParts[5]);
            double refundAmount;
            long days = diff / (24 * 60 * 60 * 1000);
            if (days >= 1) {
                refundAmount = price;
                System.out.println("提前一天以上退票，全额退款！");
            } else {
                refundAmount = price * 0.9;
                System.out.println("提前不足一天退票，扣除10%手续费！");
            }

            // 7. 获取座位图
            char[][] seatMap = targetShow.getSeatMap();
            String[] seats = saleParts[3].split(";");

            // 8. 释放座位
            for (String seat : seats) {
                String[] coords = seat.split(",");
                int row = Integer.parseInt(coords[0]) - 1;
                int col = Integer.parseInt(coords[1]) - 1;

                if (row >= 0 && row < targetShow.getRows() &&
                        col >= 0 && col < targetShow.getCols() &&
                        seatMap[row][col] == 'X') { // 确保座位当前是已售状态
                    seatMap[row][col] = 'O';
                }
            }

            // 9. 保存更新后的场次信息
            Show.saveShows(shows);

            // 10. 更新销售记录为已退票
            sales.set(targetIndex, saleParts[0] + "|" + saleParts[1] + "|" +
                    saleParts[2] + "|" + saleParts[3] + "|" +
                    saleParts[4] + "|" + saleParts[5] + "|" +
                    saleParts[6] + "|true");

            // 11. 保存销售记录
            BufferedWriter saleBw = new BufferedWriter(new FileWriter(saleFile));
            for (String s : sales) {
                saleBw.write(s);
                saleBw.newLine();
            }
            saleBw.close();

            // 12. 显示退票信息
            System.out.println("\n===== 退票成功 =====");
            System.out.println("电子票号: " + ticketId);
            System.out.println("影片名: " + movieName);
            System.out.println("放映厅: " + theaterName);
            System.out.println("放映时间: " + showTimeStr);
            System.out.println("退款金额: " + String.format("%.2f", refundAmount) + "元");
            System.out.println("====================");

            log("用户 " + username + " 退票，票号: " + ticketId + "，影片: " + movieName);

        } catch (ParseException e) {
            System.out.println("日期格式错误：" + e.getMessage());
            log("日期格式错误：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("退票失败：" + e.getMessage());
            log("退票失败：" + e.getMessage());
        } catch (Exception e) {
            System.out.println("退票失败：" + e.getMessage());
            log("退票失败：" + e.getMessage());
        }
    }

    // 记录日志
    public void log(String message) {
        try {
            // 确保目录存在
            File logDir = new File("D:\\java实训大作业");
            if (!logDir.exists()) {
                logDir.mkdirs();
            }

            BufferedWriter bw = new BufferedWriter(new FileWriter(LOG_FILE, true));
            String logMessage = "[" + sdf.format(new Date()) + "] " + message;
            bw.write(logMessage);
            bw.newLine();
            bw.close();
        } catch (IOException e) {
            System.out.println("记录日志失败：" + e.getMessage());
        }
    }
}
